import {ScannerResult} from "../../types";
import path from "path";
import fs from "fs-extra";
import folderSize from "../../utils/folderSize";
import {FormatUtil} from "../../utils/FormatUtil";

/**
 * Uniapp项目扫描器
 * 通过检测manifest.json文件来识别Uniapp项目
 */
export async function UniappScanner(projectPath: string): Promise<ScannerResult | null> {
  try {
    // 检查是否存在manifest.json文件
    const manifestPath = path.join(projectPath, 'manifest.json');
    
    if (!await fs.pathExists(manifestPath)) {
      return null;
    }
    
    // 读取manifest.json文件
    const manifest = await fs.readJSON(manifestPath);
    
    // 检查package.json
    let packageJson: any = {};
    const packageJsonPath = path.join(projectPath, 'package.json');
    if (await fs.pathExists(packageJsonPath)) {
      packageJson = await fs.readJSON(packageJsonPath);
    }
    
    // 计算项目大小
    const totalSize = await folderSize.loose(projectPath);
    let nodeModulesSize = 0;
    
    if (await fs.pathExists(path.join(projectPath, 'node_modules'))) {
      nodeModulesSize = await folderSize.loose(path.join(projectPath, 'node_modules'));
    }
    
    // 提取基本信息
    const appName = manifest.name || packageJson.name || path.basename(projectPath);
    const appVersion = manifest.versionName || packageJson.version || '未知';
    const appDesc = manifest.description || packageJson.description || '无描述';
    
    // 获取页面列表
    const pages = manifest.pages || [];
    
    // 获取支持的平台
    const platforms: string[] = [];
    if (manifest['app-plus']) platforms.push('APP');
    if (manifest['h5']) platforms.push('H5');
    if (manifest['mp-weixin']) platforms.push('微信小程序');
    if (manifest['mp-alipay']) platforms.push('支付宝小程序');
    if (manifest['mp-baidu']) platforms.push('百度小程序');
    if (manifest['mp-toutiao']) platforms.push('字节跳动小程序');
    if (manifest['mp-qq']) platforms.push('QQ小程序');
    if (manifest['quickapp-webview']) platforms.push('快应用');
    
    return {
      projectName: appName,
      basicInfo: [
        {"名称": appName},
        {"类型": "uni-app"},
        {"路径": projectPath},
        {"大小": FormatUtil.formatFileSize(totalSize)},
        {"node_modules 大小": FormatUtil.formatFileSize(nodeModulesSize)},
        {"描述": appDesc},
        {"版本": appVersion},
        {"应用ID": manifest.appid || '未设置'},
        {"支持平台": platforms.join(', ') || '未配置'},
      ],
      mores: [
        {
          title: "页面列表",
          type: "table",
          list: pages.map((page: string, index: number) => ({
            index: index + 1,
            path: page
          }))
        },
        {
          title: "配置详情",
          type: "json",
          content: JSON.stringify(manifest, null, 2),
          list: []
        }
      ]
    };
  } catch (error) {
    console.error(`扫描 uni-app 项目失败: ${projectPath}`, error);
    return null;
  }
} 